<template>
  <a-layout>
    <a-layout-header class="bg-white admin-content-header">
      <div class="col-4 admin-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col-8 text-right">
        <el-button-group>
          <el-button type="primary" @click="dialog(false)" icon="el-icon-edit">添加课程</el-button>
        </el-button-group>
      </div>

      <el-dialog :title="`${title}课程`" :top="'7vh'" :visible.sync="dialogFormVisible">
        <el-form ref="form" :rules="rules2" :model="form" label-width="100px">
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="选取图片" prop="banner">
            <el-input :value="form.banner" disabled>
              <el-button @click="innerVisible = true" slot="prepend">选取图片</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="课程简介">
            <el-input v-model="form.info"></el-input>
          </el-form-item>
          <el-form-item label="课程详细介绍">
            <el-input v-model="form.introduction"></el-input>
          </el-form-item>
          <el-form-item label="课程难度" prop="level">
            <el-select v-model="form.level" placeholder="请选择课程难度">
              <el-option label="level 1" value="level 1"></el-option>
              <el-option label="level 2" value="level 2"></el-option>
              <el-option label="level 3" value="level 3"></el-option>
              <el-option label="level 4" value="level 4"></el-option>
              <el-option label="level 5" value="level 5"></el-option>
              <el-option label="level 6" value="level 6"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程星级">
            <el-rate v-model="form.difficulty"></el-rate>
          </el-form-item>
          <el-form-item label="课程标签">
            <el-tooltip class="item" effect="dark" content="按回车键完成单个标签输入" placement="top">
              <el-select
                style="display:block;"
                v-model="Tags"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择文章标签"
              >
                <el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="课程排序">
            <el-tooltip class="item" effect="dark" content="小的在前" placement="top-start">
              <el-input-number v-model="form.paixu" :step="1"></el-input-number>
            </el-tooltip>
          </el-form-item>
          <el-tooltip
            class="item"
            effect="dark"
            content="为用户提供scratch模版！！！不要随便选择"
            placement="top-start"
          >
            <el-form-item label="课程模版" prop="iframeid" title>
              <el-select v-model="form.iframeid" placeholder="请选择课程类型">
                <el-option label="取消选择" :value="null"></el-option>
                <el-option
                  v-for="(item, index) in getIframe"
                  :key="index"
                  :label="item.name"
                  :value="item.ID"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-tooltip>
          <el-form-item class="text-right">
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button @click="dialog()">取消</el-button>
          </el-form-item>
          <el-dialog width="80%" title="选取图片" :visible.sync="innerVisible" append-to-body>
            <ossImglist v-bind:selected="selected"></ossImglist>
          </el-dialog>
        </el-form>
      </el-dialog>
    </a-layout-header>
    <a-layout-content class="admin-content-table">
      <el-table height="100%" :data="tableDate" style="width: 100%;">
        <el-table-column fixed prop="name" label="名称"></el-table-column>
        <el-table-column prop="paixu" label="排序" sortable width="80"></el-table-column>
        <el-table-column prop="courseTag" label="标签" width="120"></el-table-column>
        <el-table-column prop="level" label="level" width="80"></el-table-column>
        <el-table-column prop="info" label="介绍"></el-table-column>
        <el-table-column prop="difficulty" label="星级" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template slot-scope="scope">
            <span style="margin-left: 10px" v-text="gettime(scope.row.createTime)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最近修改" width="150">
          <template slot-scope="scope">
            <span style="margin-left: 10px" v-text="gettime(scope.row.updateTime)"></span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="280">
          <template slot="header">
            <input class="el-input__inner" v-model="search" placeholder="请输入内容" />
          </template>
          <template slot-scope="scope">
            <el-button class="position-relative">
              <router-link
                :to="{name:'课程详情', params: { courseId: scope.row.ID }}"
                class="stretched-link"
              >查看</router-link>
            </el-button>
            <el-button @click="dialog(scope.row)" type="warning" class="el-icon-edit-outline"></el-button>
            <el-button
              @click="deldata({cid:scope.row.ID})"
              icon="el-icon-delete"
              type="danger"
              title="删除"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </a-layout-content>
    <adminContentFooter
      v-bind="{handleSizeChange, handleCurrentChange, currentPage, pagesize,data: getCourse}"
    ></adminContentFooter>
  </a-layout>
</template>

<script>
import {
  asyncdeleteCourse,
  asyncupdateCourse,
  asyncuploadCourse
} from "../../../plugins/api.js";
import { mapGetters } from "vuex";
import { gettime } from "../../../plugins/utils";
import ossImglist from "@/components/newpublic/oss.vue";
import adminContentFooter from "@/components/admin/admin-content-footer.vue";
import { compact, uniq } from "underscore";
export default {
  data() {
    return {
      title: "查看课程",
      dialogFormVisible: false,
      innerVisible: false,
      search: "",
      form: {},
      pagesize: 10,
      currentPage: 1,
      rules2: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" }
        ],
        banner: [
          { required: true, message: "请选择一张图片", trigger: "blur" }
        ],
        level: [{ required: true, message: "请选择leavl等级", trigger: "blur" }]
      }
    };
  },
  computed: {
    ...mapGetters(["getCourse", "getIframe", "getCatebag"]),
    tableDate() {
      const { getCourse, search, currentPage, pagesize } = this;
      const data = getCourse.filter(
        data =>
          !search || data.name.toLowerCase().includes(search.toLowerCase())
      );
      return data.slice((currentPage - 1) * pagesize, currentPage * pagesize);
    },
    options() {
      const { getCourse } = this;
      const data = [];
      for (const { courseTag } of getCourse) {
        if (courseTag) {
          const arr = courseTag.split(",");
          data.push(...arr);
        }
      }
      return uniq(compact(data));
    },
    Tags: {
      get() {
        const { form } = this;
        const { courseTag } = form;
        if (courseTag) {
          return courseTag.split(",");
        }
        return [];
      },
      set(value) {
        this.form.courseTag = value.join(",");
      }
    }
  },
  methods: {
    gettime,
    handleSizeChange(val) {
      this.pagesize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    dialog(i) {
      if (i) {
        this.title = "修改";
        this.form = JSON.parse(JSON.stringify(i));
      } else {
        this.title = "添加";
        this.form = {
          banner: null,
          catebagid: null,
          coursePrize: 0,
          courseTag: null,
          courseType: " ",
          createTime: null,
          difficulty: 0,
          environment: null,
          hot: null,
          iframeid: null,
          info: "",
          introduction: null,
          level: null,
          name: "",
          paixu: 0,
          teacher_ID: null,
          updateTime: null
        };
      }
      this.dialogFormVisible = true;
    },
    selected(v) {
      this.form.banner = v;
      this.innerVisible = false;
    },
    async onSubmit() {
      const { form, name } = this;
      try {
        if (form.ID) {
          await asyncupdateCourse(form);
        } else {
          await asyncuploadCourse(form);
        }
        this.$store.dispatch("actionCourse");
        this.$message({
          message: `恭喜你，${name}成功`,
          type: "success"
        });
        this.dialogFormVisible = false;
      } catch (err) {
        this.$message.error(`错了哦，${name}失败: ${err}`);
      }
    },
    async deldata(i) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asyncdeleteCourse(i);
            this.$store.dispatch("actionCourse");
            this.$message({
              message: "恭喜你，删除成功",
              type: "success"
            });
          } catch (err) {
            this.$message.error("错了哦，删除失败:" + err);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    querySearch(queryString, cb) {
      var restaurants = this.getCourse;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    }
  },
  components: {
    ossImglist,
    adminContentFooter
  }
};
</script>

<style scoped>
</style>